package com.sky.utils;

import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;

@Data
@AllArgsConstructor
@Slf4j
public class HuaWeiObsUtil {

    private static final String endpoint = "obs.cn-east-3.myhuaweicloud.com";
    private static final String accessKeyId = "KXU78CN792LRHCFT4BKS";
    private static final String secretAccessKey = "2ATa3W3POEIceC7SgNmElt7rA1lPVUIHGURKE5EX";
    private static final String bucketName = "sky-cast";

    /**
     * 文件上传
     * @param objectName
     * @param in
     * @return
     */

    public static String upload(String objectName, InputStream in) {

        // 创建ObsClient实例
        ObsClient obsClient = new ObsClient(accessKeyId,secretAccessKey,endpoint);

        try {
            obsClient.putObject(bucketName, objectName, in);
        } catch (ObsException e) {
            System.out.println("putObject failed");
            // 请求失败,打印http状态码
            System.out.println("HTTP Code:" + e.getResponseCode());
            // 请求失败,打印服务端错误码
            System.out.println("Error Code:" + e.getErrorCode());
            // 请求失败,打印详细错误信息
            System.out.println("Error Message:" + e.getErrorMessage());
            // 请求失败,打印请求id
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("文件上传失败...");
            // 其他异常信息打印
            e.printStackTrace();
        }

        //文件访问路径规则 https://BucketName.Endpoint/ObjectName
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(objectName);

        log.info("文件上传到:{}", stringBuilder.toString());

        return stringBuilder.toString();
    }
}
